// 找出所有相加之和为 n 的 k 个数的组合。组合中只允许含有 1 - 9 的正整数，并且每种组合中不存在重复的数字。

// 说明：

// 所有数字都是正整数。
// 解集不能包含重复的组合。 
// 示例 1:

// 输入: k = 3, n = 7
// 输出: [[1,2,4]]
// 示例 2:

// 输入: k = 3, n = 9
// 输出: [[1,2,6], [1,3,5], [2,3,4]]

#include <vector>

using namespace std;

/* 回溯
*/
class Solution {
public:
    vector<vector<int>> combinationSum3(int k, int n) {
        vector<vector<int>> res{};
        vector<int> vec{};
        vector<int> nums{1,2,3,4,5,6,7,8,9};
        backTrack(res, vec, nums, 0, k, n);
        return res;
    }
    void backTrack(vector<vector<int>>& res, vector<int>& vec, const vector<int>& nums, int start, const int& k, int target) {
        if (target == 0 && vec.size() == k) {
            res.push_back(vec);
        } else {
            for (int i{start}; i < nums.size(); ++i) {
                if (target - nums[i] < 0) break;
                vec.push_back(nums[i]);
                backTrack(res, vec, nums, i + 1, k, target - nums[i]);
                vec.pop_back();
            }
        }
    }
};

/* 回溯
*/
class Solution {
public:
    vector<vector<int>> combinationSum3(int k, int n) {
        vector<vector<int>> res{};
        vector<int> vec{};
        vector<int> nums{1,2,3,4,5,6,7,8,9};
        backTrack(res, vec, nums, 0, k, n);
        return res;
    }
    void backTrack(vector<vector<int>>& res, vector<int>& vec, const vector<int>& nums, int start, int k, int target) {
        if (target == 0 && k == 0) {
            res.push_back(vec);
        } else {
            for (int i{start}; i < nums.size(); ++i) {
                if (target - nums[i] < 0) break;
                vec.push_back(nums[i]);
                backTrack(res, vec, nums, i + 1, k - 1, target - nums[i]);
                vec.pop_back();
            }
        }
    }
};

class Solution {
public:
    vector<vector<int>> combinationSum3(int k, int n) {
        dfs(1, k, n);
        return res;
    }
    void dfs(int start, const int& k, int n) {
        if (temp.size() == k && n == 0) {
            res.emplace_back(temp);
            return;
        }
        if (n < 0) {
            return;
        }
        for (int i{start}; i <= 9; ++i) {
            temp.push_back(i);
            dfs(i + 1, k, n - i);
            temp.pop_back();
        }
    }
private:
    vector<vector<int>> res{};
    vector<int> temp{};
};